import Mock from 'mockjs'
import { brandData, newFoodData, PackageData, commentData, financialData } from '@/api/mockData/brandData'
import { mockStores } from './mockData/storesData';
import type { StoreInfo } from "@/Interface/StoreInfoInterface";
import { enc, SHA256 } from 'crypto-js';

// 品牌基础信息接口
Mock.mock(/\/api\/brand/, 'get', () => ({
  code: 200,
  data: brandData,
  message: '品牌数据获取成功'
}))

// 新品上市接口
Mock.mock(/\/api\/newfood/, 'get', () => ({
  code: 200,
  data: newFoodData,
  message: '新品数据获取成功'
}))

// 套餐推荐接口
Mock.mock(/\/api\/package/, 'get', () => ({
  code: 200,
  data: PackageData,
  message: '套餐数据获取成功'
}))

// 用户评论接口
Mock.mock(/\/api\/comments/, 'get', () => {
  return {
    code: 200,
    data: commentData,
    message: '评论数据获取成功'
  }
})

// 财务数据接口
Mock.mock(/\/api\/financials/, 'get', () => {
  return {
    code: 200,
    data: financialData,
    message: '财务数据获取成功'
  }
})



// 全部门店信息接口
Mock.mock(/\/api\/storesData/, 'get', () => ({
  code: 200,
  data: mockStores,
  message: '全部门店数据获取成功'
}));

// 门店统计信息接口
Mock.mock(/\/api\/stores\/stats/, 'get', () => {
  // 统计逻辑
  const stats = {
    total: mockStores.length,
    typeData: (() => {
      const typeCounts = mockStores?.reduce((acc, store) => {
        const type = store.basicInfo.storeType;
        acc[type] = (acc[type] || 0) + 1;
        return acc;
      }, {} as Record<string, number>) || {};

      return Object.entries(typeCounts).map(([name, value]) => ({
        name,
        value
      }));
    })(),
    tagsData: (() => {
      const typeCounts = mockStores?.reduce((acc, store) => {
        const type = store.basicInfo.tags[0];
        acc[type] = (acc[type] || 0) + 1;
        return acc;
      }, {} as Record<string, number>) || {};
      return Object.entries(typeCounts).map(([name, value]) => ({
        name,
        value
      }));
    })(),
    topStores: mockStores
      .sort((a, b) => b.annualData.yearAmount - a.annualData.yearAmount)
      .slice(0, 5)
  }

  return {
    code: 200,
    data: stats,
    message: '统计信息获取成功'
  }
})

// 创建门店
Mock.mock(/\/api\/stores/, 'post', (config) => {
  const stored = localStorage.getItem('stores-list')
  const storesList = stored ? JSON.parse(stored) : mockStores.map((store: StoreInfo) => {
    return {
      basicInfo: {
        storeId: store.basicInfo.storeId,
        storeName: store.basicInfo.storeName,
        province: store.basicInfo.province,
        city: store.basicInfo.city,
        coordinates: {
          lng: store.basicInfo.coordinates.lng,
          lat: store.basicInfo.coordinates.lat
        },
        storeType: store.basicInfo.storeType,
        areaSize: Number(store.basicInfo.areaSize),
        openingDate: store.basicInfo.openingDate,
        tags: [store.basicInfo.tags]
      }
    }
  })

  const newStore = JSON.parse(config.body)

  // 数据校验
  if (storesList.some((store: StoreInfo) => store.basicInfo.storeId === newStore.basicInfo.storeId)) {
    return { code: 409, message: '门店ID已存在' }
  }

  storesList.unshift(newStore)
  localStorage.setItem('stores-list', JSON.stringify(storesList))

  return { code: 200, data: newStore, message: '创建成功' }
})

// 更新门店
Mock.mock(/\/api\/stores\/[\w-]+/, 'put', (config) => {
  const stored = localStorage.getItem('stores-list')
  const storesList = stored ? JSON.parse(stored) : mockStores

  const id = config.url.split('/').pop()
  const index = storesList.findIndex((store: StoreInfo) => store.basicInfo.storeId === id)
  if (index === -1) return { code: 404, message: '门店不存在' }

  const updateData = JSON.parse(config.body)

  // 合并数据
  storesList[index] = {
    ...storesList[index], // 保留原有数据
    ...updateData         // 覆盖新字段
  }
  localStorage.setItem('stores-list', JSON.stringify(storesList))

  return { code: 200, data: storesList[index], message: '更新成功' }
})

// 删除门店
Mock.mock(/\/api\/stores\/[\w-]+/, 'delete', (config) => {
  const stored = localStorage.getItem('stores-list')
  const storesList = stored ? JSON.parse(stored) : mockStores

  const id = config.url.split('/').pop()
  const index = storesList.findIndex((store: StoreInfo) => store.basicInfo.storeId === id)
  if (index === -1) return { code: 404, message: '门店不存在' }

  storesList.splice(index, 1)
  localStorage.setItem('stores-list', JSON.stringify(storesList))

  return { code: 200, message: '删除成功' }
})

// 分页数据接口
Mock.mock(/\/api\/stores\/paged/, 'get', (config: any) => {
  const stored = localStorage.getItem('stores-list')
  const storesList = stored ? JSON.parse(stored) : mockStores

  const url = new URL(config.url, 'http://localhost');
  const page = parseInt(url.searchParams.get('page') || '1');
  const pageSize = parseInt(url.searchParams.get('pageSize') || '8');

  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const paginatedData = storesList.slice(start, end)

  return {
    code: 200,
    data: {
      list: paginatedData.map((store: StoreInfo) => ({
        storeId: store.basicInfo.storeId,
        storeName: store.basicInfo.storeName,
        storeType: store.basicInfo.storeType,
        province: store.basicInfo.province,
        city: store.basicInfo.city,
        openingDate: store.basicInfo.openingDate,
        areaSize: store.basicInfo.areaSize,
        tags: store.basicInfo.tags,
        coordinates: store.basicInfo.coordinates
      })),
      pagination: {
        current: page,
        pageSize: pageSize,
        total: storesList.length,
        totalPages: Math.ceil(storesList.length / pageSize),
      }
    },
    message: '分页数据获取成功'
  };
});

// 搜索门店
Mock.mock(/\/api\/stores\/search/, 'get', (config) => {
  const stored = localStorage.getItem('stores-list')
  const storesList = stored ? JSON.parse(stored) : mockStores

  // 解析请求参数
  const urlParams = new URLSearchParams(config.url.split('?')[1] || '');
  const keyword = urlParams.get('keyword') || '';
  // /api/stores/search?keyword=123 → 得到 "123"

  const page = parseInt(urlParams.get('page') || '1');
  const pageSize = parseInt(urlParams.get('pageSize') || '8');

  const searchResult = storesList.filter((store: StoreInfo) => {
    return (
      store.basicInfo.storeId.includes(keyword) ||
      store.basicInfo.storeName.includes(keyword)
    );
  });

  // 分页处理
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const paginatedData = searchResult.slice(start, end);

  return {
    code: 200,
    data: {
      list: paginatedData.map((store: StoreInfo) => ({
        storeId: store.basicInfo.storeId,
        storeName: store.basicInfo.storeName,
        storeType: store.basicInfo.storeType,
        province: store.basicInfo.province,
        city: store.basicInfo.city,
        openingDate: store.basicInfo.openingDate,
        tags: store.basicInfo.tags,
        coordinates: store.basicInfo.coordinates,
        areaSize: store.basicInfo.areaSize
      })),
      pagination: {
        current: page,
        pageSize: pageSize,
        total: searchResult.length,
        totalPages: Math.ceil(storesList.length / pageSize),
      }
    },
    message: '搜索成功'
  };
});


// 登录接口
Mock.mock(/\/api\/auth\/login/, 'post', (config) => {
  const { username, password: receivedHash, salt } = JSON.parse(config.body);

  // 查找用户
  const user = users.find(user => user.username === username);

  // 验证用户名
  if (!user) {
    return {
      code: 401,
      message: '用户名或密码错误'
    };
  }

  // 计算预期哈希值
  const expectedHash = enc.Base64.stringify(SHA256(user.password + salt));

  // 比较哈希值
  if (receivedHash === expectedHash) {
    return {
      code: 200,
      data: {
        token: 'mock-token-' + Mock.Random.guid(),
        user: {
          id: user.id,
          username: user.username,
          name: user.name,
          role: user.role,
          src: user.src
        }
      },
      message: '登录成功'
    };
  }

  return {
    code: 401,
    message: '用户名或密码错误'
  };
});

// 用户数据库
const users = [
  {
    id: 1,
    username: 'admin',
    password: 'admin',
    role: 'admin',
    name: '系统管理员',
    src: 'assets/images/admin.jpg'
  },
  {
    id: 2,
    username: 'user',
    password: 'user',
    role: 'user',
    name: '普通用户',
    src: 'assets/images/user.jpg'
  }
];